package com.codejoys.ssm.web;

import com.codejoys.ssm.dao.ThesisDao;
import com.codejoys.ssm.domain.Thesis;
import com.codejoys.ssm.dto.BaseResult;
import com.codejoys.ssm.service.ThesisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
public class ThesisController {
    private static final Logger logger = LoggerFactory.getLogger(ThesisController.class);
    @Autowired
    ThesisService thesisService;
    @Autowired
    ThesisDao thesisDao;

    @PostMapping("/theses")
    public BaseResult insert(Thesis thesis){

        //获取当前用户的ID(老师的id),设到课题的u_id属性里去

        thesis.setUid(1L); //todo FIXME 设置成当前用户的id

        thesis.setCreated(new Date());
        thesis.setUpdated(new Date());
        thesis.setCreatedBy(1L);
        thesis.setUpdatedBy(1L);

        thesisService.insert(thesis);

        return BaseResult.success();
    }

    @Value("${tms.response.code1}")
    private String contant;

    @PutMapping("/theses/{id}")
    public BaseResult update(Thesis thesis, @PathVariable("id") Integer tid){

        thesis.setId(tid);
        thesis.setUpdated(new Date());
        thesisService.update(thesis);
        return BaseResult.success();
    }
    // Authentication: 包含了当前用户的身份信息
    @DeleteMapping("/theses/{id}")
    public  BaseResult delete(@PathVariable("id") Integer id, Authentication auth){
        // 获取当前用户信息
        logger.debug("用户名字：{}", auth.getName());
        logger.debug("用户权限：{}", auth.getAuthorities());



        thesisService.delete(id);
        return BaseResult.success();
    }

    @GetMapping("/teachers/{teacherId}/theses")//?year=2020
    public BaseResult findThesesOfTeacher(
            @PathVariable("teacherId") Long teacherId, @PathVariable("year") short year) {
       // thesisDao.findThesesOfTeacher(teacherId, year);

        logger.debug("自定义的常量值：{}", contant);
        return BaseResult.success();

    }


    // 需要有student权限才能调用
    @PreAuthorize("hasRole('student')")
    @PostMapping("/students/{studentId}/theses/{thesisId}")
    public BaseResult chooseThesis(
            @PathVariable("studentId") Long sid,
            @PathVariable("thesisId") Integer tid){
        thesisService.chooseThesis(sid, tid);
        return BaseResult.success();
    }


    @PostMapping("theses/{thesisId}/students/{studentId}")
    public BaseResult chooseStudent(
            @PathVariable("thesisId") Integer tid,
            @PathVariable("studentId") Long sid){
        thesisService.chooseStudent(tid, sid);
        return BaseResult.success();
    }



}
